package com.iotimc.attendancesystem.attendance;

import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iotimc.attendancesystem.Contract;
import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.base.BaseFragment;
import com.iotimc.attendancesystem.dao.GreenDaoManager;
import com.iotimc.attendancesystem.dao.SystemEntityDao;
import com.iotimc.attendancesystem.entity.SystemEntity;
import com.iotimc.attendancesystem.util.PictureManager;
import com.iotimc.attendancesystem.util.ShareUtil;
import com.iotimc.networklibrary.core.HttpRetrofitFactory;

import java.io.File;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

/**
 * Created by cwj on 2017/11/28.
 */

public class MainFragment extends BaseFragment {
    private static final String TAG = "WeatherFragment";
    @BindView(R.id.iv_system_main_bg)
    ImageView mIvSystemMainBg;
    @BindView(R.id.iv_system_main_title)
    TextView mIvSystemMainTitle;
    @BindView(R.id.iv_system_main_message)
    TextView mIvSystemMainMessage;
    @BindView(R.id.iv_weather_now_cond)
    ImageView nowCond;
    @BindView(R.id.tv_weather_now_tmp)
    TextView nowTmp;
    @BindView(R.id.iv_weather_now_fl)
    TextView nowFl;
    @BindView(R.id.iv_weather_now_hum)
    TextView nowHum;
    @BindView(R.id.iv_weather_tomorrow)
    ImageView tomorrowImg;
    @BindView(R.id.tv_weather_tomorrow)
    TextView tomorrowText;
    @BindView(R.id.iv_weather_after)
    ImageView afterImg;
    @BindView(R.id.tv_weather_after)
    TextView afterText;
    @BindView(R.id.tv_weather_date)
    TextView dateText;
    @BindView(R.id.ll_weather)
    LinearLayout mLinearLayoutWeather;
    @BindView(R.id.iv_system_main_notice)
    TextView mIvSystemMainNotice;
    @BindView(R.id.ll_announcement)
    LinearLayout mLlAnnouncement;
    Unbinder unbinder;
    private String baseUrl = "https://free-api.heweather.com/s6/weather";
    private String ipUrl = "http://httpbin.org/ip";
    private String key = "beb4f7fc27ae4f6e8a3cf1180da0b503";
    private String location = "";


    @OnClick(R.id.ll_weather)
    void updateTemp() {
        getTemp();
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_main;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getTemp();
        getNotice();
    }

    private void setWeatherImg(ImageView view, int code) {
        int img = R.drawable.weather_999;
        switch (code) {
            case 100:
                img = R.drawable.weather_100;
                break;
            case 101:
                img = R.drawable.weather_101;
                break;
            case 102:
                img = R.drawable.weather_102;
                break;
            case 103:
                img = R.drawable.weather_103;
                break;
            case 104:
                img = R.drawable.weather_104;
                break;
            case 200:
                img = R.drawable.weather_200;
                break;
            case 201:
                img = R.drawable.weather_201;
                break;
            case 202:
                img = R.drawable.weather_202;
                break;
            case 203:
                img = R.drawable.weather_203;
                break;
            case 204:
                img = R.drawable.weather_204;
                break;
            case 205:
                img = R.drawable.weather_205;
                break;
            case 206:
                img = R.drawable.weather_206;
                break;
            case 207:
                img = R.drawable.weather_207;
                break;
            case 208:
                img = R.drawable.weather_208;
                break;
            case 209:
                img = R.drawable.weather_209;
                break;
            case 210:
                img = R.drawable.weather_210;
                break;
            case 211:
                img = R.drawable.weather_211;
                break;
            case 212:
                img = R.drawable.weather_212;
                break;
            case 213:
                img = R.drawable.weather_213;
                break;
            case 300:
                img = R.drawable.weather_300;
                break;
            case 301:
                img = R.drawable.weather_301;
                break;
            case 302:
                img = R.drawable.weather_302;
                break;
            case 303:
                img = R.drawable.weather_303;
                break;
            case 304:
                img = R.drawable.weather_304;
                break;
            case 305:
                img = R.drawable.weather_305;
                break;
            case 306:
                img = R.drawable.weather_306;
                break;
            case 307:
                img = R.drawable.weather_307;
                break;
            case 308:
                img = R.drawable.weather_308;
                break;
            case 309:
                img = R.drawable.weather_309;
                break;
            case 310:
                img = R.drawable.weather_310;
                break;
            case 311:
                img = R.drawable.weather_311;
                break;
            case 312:
                img = R.drawable.weather_312;
                break;
            case 313:
                img = R.drawable.weather_313;
                break;
            case 400:
                img = R.drawable.weather_400;
                break;
            case 401:
                img = R.drawable.weather_401;
                break;
            case 402:
                img = R.drawable.weather_402;
                break;
            case 403:
                img = R.drawable.weather_403;
                break;
            case 404:
                img = R.drawable.weather_404;
                break;
            case 405:
                img = R.drawable.weather_405;
                break;
            case 406:
                img = R.drawable.weather_406;
                break;
            case 407:
                img = R.drawable.weather_407;
                break;
            case 500:
                img = R.drawable.weather_500;
                break;
            case 501:
                img = R.drawable.weather_501;
                break;
            case 502:
                img = R.drawable.weather_502;
                break;
            case 503:
                img = R.drawable.weather_503;
                break;
            case 504:
                img = R.drawable.weather_504;
                break;
            case 507:
                img = R.drawable.weather_507;
                break;
            case 508:
                img = R.drawable.weather_508;
                break;
            case 900:
                img = R.drawable.weather_900;
                break;
            case 901:
                img = R.drawable.weather_901;
                break;
            case 999:
                img = R.drawable.weather_999;
                break;
            default:
                break;
        }
        PictureManager.getInstance().load(getActivity(), img, view, true);
    }

    public void getTemp() {
        Observable<JSONObject> resultToObject = HttpRetrofitFactory.getInstance().getResultToObject(ipUrl, new HashMap(1));
        resultToObject.flatMap(new Function<JSONObject, ObservableSource<JSONObject>>() {
            @Override
            public ObservableSource<JSONObject> apply(JSONObject object) throws Exception {
                location = object.getString("origin");
                if (!TextUtils.isEmpty(location)) {
                    HashMap<String, String> map = new HashMap<>(2);
                    map.put("key", key);
                    map.put("location", location);
                    return HttpRetrofitFactory.getInstance().getResultToObject(baseUrl, map);
                }
                return null;
            }
        }).subscribe(new Observer<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                Log.d(TAG, "accept: " + value.toString());
                setNowTmp(value);
                ShareUtil.saveString(getContext(), value.toJSONString(), Contract.WEATHER);

            }

            @Override
            public void onError(Throwable e) {
                String weather = ShareUtil.getString(getContext(), "", Contract.WEATHER);
                if (!TextUtils.isEmpty(weather)) {
                    JSONObject jsonObject = JSONObject.parseObject(weather);
                    setNowTmp(jsonObject);
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void setNowTmp(JSONObject value) {
        JSONObject weather6 = (JSONObject) value.getJSONArray("HeWeather6").get(0);
        JSONObject now = weather6.getJSONObject("now");

        //温度，默认单位：摄氏度
        String tmp = now.getString("tmp") + "°";
        nowTmp.setText(tmp);
        //实况天气状况代码
        String condCode = now.getString("cond_code");
        setWeatherImg(nowCond, Integer.valueOf(condCode));
        //实况天气状况代码
        String condTxt = now.getString("cond_txt");
        //相对湿度
        String hum = now.getString("hum");
        String humText = "相对湿度  " + hum + "%";
        nowHum.setText(humText);
        //体感温度，默认单位：摄氏度
        String fl = now.getString("fl");
        String flText = "体感温度   " + fl + "°";
        nowFl.setText(flText);


        //更新时间
        String loc = "更新时间" + weather6.getJSONObject("update").getString("loc");
        dateText.setText(loc);

        JSONArray dailyForecast = weather6.getJSONArray("daily_forecast");
        for (int count = 0; dailyForecast.size() > count; count++) {
            JSONObject jsonObject = (JSONObject) dailyForecast.get(count);
            //tmp_min  最低温度
            String tmpMin = jsonObject.getString("tmp_min");
            //tmp_max  最高温度
            String tmpMax = jsonObject.getString("tmp_max");
            String tmpInfo = tmpMin + "°~" + tmpMax + "°";
            //白天天气状况代码
            int condCodeD = Integer.valueOf(jsonObject.getString("cond_code_d"));
            if (count == 1) {
                tomorrowText.setText(tmpInfo);
                setWeatherImg(tomorrowImg, condCodeD);
            } else if (count == 2) {
                afterText.setText(tmpInfo);
                setWeatherImg(afterImg, condCodeD);
            }

        }
    }

    public void getNotice() {
        SystemEntityDao systemEntityDao = GreenDaoManager.getInstance().getSession().getSystemEntityDao();
        SystemEntity systemEntity = systemEntityDao.load(1L);
        if (systemEntity != null) {
            String notice = systemEntity.getNotice();
            String content = systemEntity.getContent();
            String title = systemEntity.getTitle();
            //String img64 = systemEntity.getImg64();
            File directory = Environment.getExternalStorageDirectory();
            File[] files = directory.listFiles();
            File attendance = null;
            for (File file : files) {
                if (file.getName().contains("attendanceImg")) {
                    attendance = file;
                    break;
                }
            }

            if (!TextUtils.isEmpty(content)) {
                mIvSystemMainMessage.setText(content);
            }

            if (attendance != null && attendance.exists()) {
                //PictureManager.getInstance().load(getContext(), PictureManager.getInstance().getArray64(img64), mIvSystemMainBg, false);
                PictureManager.getInstance().load(getContext(), attendance, mIvSystemMainBg, false);
            }

            if (!TextUtils.isEmpty(title)) {
                mIvSystemMainTitle.setText(title);
            }

            if (!TextUtils.isEmpty(notice)) {
                mIvSystemMainNotice.setText(notice);
            }
        }
    }
}
